package hn.cch.spring_async_call.filter;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 过滤器
 */
@WebFilter(filterName = "apiFilter", urlPatterns = "/api/*")
public class ApiFilter extends OncePerRequestFilter {

    private static Logger logger = LoggerFactory.getLogger(ApiFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            long start = System.currentTimeMillis(); // 请求进入时间
            logger.info("######################################## [{}:{}]", httpServletRequest.getMethod(), httpServletRequest.getRequestURI());
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            logger.info("######################################## [{}:{}ms] \n\n", httpServletRequest.getRequestURI(), (System.currentTimeMillis() - start));
        } finally {
            MDC.clear();
        }

    }
}
